<template>
    <el-container class="admin-container">
      <!-- 搜索框 -->
      <el-header class="search-header">
        <el-row :gutter="20" justify="space-between" align="middle">
          <el-col :span="8">
            <el-input v-model="searchForm.name" placeholder="咨询师姓名" clearable>
              <template #prefix><i class="el-icon-search"></i></template>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-input v-model="searchForm.tel" placeholder="电话号码" clearable>
              <template #prefix><i class="el-icon-search"></i></template>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
            <el-button plain icon="Refresh" @click="resetSearchForm">重置</el-button>
            <el-button plain icon="Plus" @click="handleAdd">新增咨询师</el-button>
          </el-col>
        </el-row>
      </el-header>
  
      <!-- 咨询师表格 -->
      <el-main class="main-content">
        <el-table
          :data="consultants"
          stripe
          border
          style="width: 100%"
          v-loading="loading"
          element-loading-text="加载中..."
          :header-cell-style="{ background: '#f5f7fa' }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="username" label="咨询师姓名" width="180" />
          <el-table-column prop="tel" label="电话号码" width="180" />
          <el-table-column label="头像" width="120">
            <template #default="{ row }">
              <el-avatar :src="row.tx"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="真实姓名" width="180" />
          <el-table-column label="简介" width="300">
            <template #default="{ row }">
              <el-tooltip :content="row.intro" placement="top">
                <span class="ellipsis">{{ row.intro }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="是否有证书">
            <template #default="{ row }">
              <el-tag :type="row.isCertified ? 'success' : 'info'">
                {{ row.isCertified ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="是否禁用">
            <template #default="{ row }">
              <el-tag :type="row.isDisabled ? 'danger' : 'success'">
                {{ row.isDisabled ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="240">
            <template #default="scope">
              <el-button type="info" size="small" @click="handleDetail(scope.row)">详情</el-button>
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDeleteConfirm(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页组件 -->
        <div class="pagination-wrapper">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[5, 10, 15, 20]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
  
      <!-- 弹窗组件 -->
      <el-dialog
        v-model="dialogVisible"
        :title="currentDialogType === 'add' ? '添加咨询师' : currentDialogType === 'edit' ? '编辑咨询师' : '咨询师详情'"
        :width="currentDialogType === 'detail' ? '80%' : '600px'"
        class="admin-dialog"
      >
        <el-form
          ref="formRef"
          :model="consultantInfo"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="咨询师姓名" prop="username">
                <el-input v-model="consultantInfo.username" :disabled="currentDialogType === 'detail'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="真实姓名" prop="name">
                <el-input v-model="consultantInfo.name" :disabled="currentDialogType === 'detail'" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电话" prop="tel">
                <el-input v-model="consultantInfo.tel" :disabled="currentDialogType === 'detail'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input v-model="consultantInfo.password" type="password" :disabled="currentDialogType === 'detail'" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="简介" prop="intro">
                <el-input v-model="consultantInfo.intro" type="textarea" :rows="4" :disabled="currentDialogType === 'detail'" />
              </el-form-item>
            </el-col>
            
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="是否有证书">
                <el-switch
                  v-model="consultantInfo.isCertified"
                    :active-value="1"
                    :inactive-value="0"
                  active-text="是"
                  inactive-text="否"
                  :disabled="currentDialogType === 'detail'"
                />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="是否禁用">
                <el-switch
                  v-model="consultantInfo.isDisabled"
                    :active-value="1"
                    :inactive-value="0"
                  active-text="是"
                  inactive-text="否"
                  :disabled="currentDialogType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="头像" prop="avatar">
                <el-upload
                  v-if="currentDialogType !== 'detail'"
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="consultantInfo.avatar" :src="consultantInfo.avatar" class="avatar" />
                  <el-icon v-else><Plus /></el-icon>
                </el-upload>
                <div v-else class="avatar-container">
                  <img :src="consultantInfo.avatar" class="avatar" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
  
        <template #footer>
          <span v-if="currentDialogType !== 'detail'">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmAction" :loading="submitLoading">
              确定
            </el-button>
          </span>
          <span v-else>
            <el-button @click="dialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-container>
  </template>
  
  <script>
import { mapState, mapActions, mapMutations } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  data() {
    return {
      loading: false,
      dialogVisible: false,
      submitLoading: false,
      currentDialogType: 'add',
      searchForm: {
        username: '',
        tel: ''
      },
      uploadUrl: 'https://your-upload-api.com',
      uploadHeaders: { 'Content-Type': 'multipart/form-data' }
    }
  },
  computed: {
    ...mapState('consultant', ['consultantList', 'pagination','consultantInfo']),
    // 计算属性
    consultants() {
      return this.consultantList
    },
    total() {
      return this.pagination.total
    },
    currentPage: {
      get() {
        return this.pagination.page
      },
      set(val) {
        this.SET_PAGINATION({ page: val })
      }
    },
    pageSize: {
      get() {
        return this.pagination.size
      },
      set(val) {
        this.SET_PAGINATION({ size: val })
      }
    }
  },
  mounted() {
    this.fetchConsultantList()
  },
  methods: {
    ...mapActions('consultant', [
      'fetchConsultantList',
      'addConsultant',
      'updateConsultant',
      'deleteConsultant'
    ]),
    ...mapMutations('consultant', ['SET_PAGINATION','SET_CONSULTANT_INFO']),

    handleSearch() {
      this.SET_PAGINATION({ 
        search: { ...this.searchForm },
        page: 1
      })
      this.fetchConsultantList()
    },

    resetSearchForm() {
      this.searchForm = {
        name: '',
        tel: ''
      }
      this.handleSearch()
    },
     // 新增详情处理方法
     handleDetail(row) {
      this.currentDialogType = 'detail'
      this.SET_CONSULTANT_INFO({ 
        ...row,
        // 转换数字类型为布尔值用于switch显示
        isCertified: row.isCertified === 1,
        isDisabled: row.isDisabled === 1
      })
      this.dialogVisible = true
    },
    handleAdd() {
      this.currentDialogType = 'add'
      this.SET_CONSULTANT_INFO({
        id: null,
        username: '',
        name: '',
        password: '',
        tel: '',
        intro: '',
        isCertified: 0,
        isDisabled: 0,
        tx: ''
      })
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.currentDialogType = 'edit'
      this.SET_CONSULTANT_INFO({ ...row })
      this.dialogVisible = true
    },

    async handleConfirmAction() {
      try {
        await this.$refs.formRef.validate()
        this.submitLoading = true

        if (this.currentDialogType === 'add') {
          await this.addConsultant(this.consultantInfo)
        } else {
          await this.updateConsultant({id: this.consultantInfo.id,data: this.consultantInfo})
        }

        this.dialogVisible = false
        ElMessage.success('操作成功')
        await this.fetchConsultantList()
      } catch (error) {
        ElMessage.error(error.message || '操作失败')
      } finally {
        this.submitLoading = false
      }
    },

    handleDeleteConfirm(row) {
      ElMessageBox.confirm(`确定删除咨询师 ${row.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.deleteConsultant(row.id)
        ElMessage.success('删除成功')
        await this.fetchConsultantList()
      }).catch(() => {})
    },

    handleSizeChange(size) {
      this.pageSize = size
      this.fetchConsultantList()
    },

    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchConsultantList()
    },

    handleAvatarSuccess(res, file) {
      this.form.tx = URL.createObjectURL(file.raw)
    },

    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        ElMessage.error('只能上传图片文件!')
      }
      return isImage
    }
  }
}
</script>
  
  <style scoped>
  .admin-container {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
  }
  
  .search-header {
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  }
  
  .main-content {
    padding: 20px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
  
  .admin-dialog {
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  }
  
  .dialog-form {
    padding: 24px;
  }
  
  .el-row {
    margin-bottom: 20px;
  }
  
  .el-col:last-child {
    margin-bottom: 0;
  }
  
  @media (max-width: 768px) {
    .el-col {
      width: 100% !important;
    }
  }
  
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  
  .avatar-container {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 100px;
  }
  </style>